package com.leather.zuul.config;

import com.alibaba.fastjson.JSON;
import com.leather.common.entity.User;
import com.leather.common.result.CodeMsg;
import com.leather.common.result.Result;
import com.leather.common.toolkits.JwtKit;
import com.leather.zuul.feignclient.UserClient;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;

import javax.servlet.http.HttpServletRequest;

@Slf4j
@Configuration//该注解是让服务器启动时将奔雷作为配置类注入到spring容器。如若不加此注解，需在启动类配置该bean
public class AccessFilter extends ZuulFilter {

    @Autowired
    private UserClient userClient;

    //可以在请求被路由之前调用
    @Override
    public String filterType() {
        return "pre";
    }

    //通过int值来定义过滤器的执行顺序，越小的值越优先处理。
    @Override
    public int filterOrder() {
        return 0;
    }

    //返回一个boolean类型来判断该过滤器是否要执行，所以通过此函数可实现过滤器的开关。true:总是生效，false:不生效
    @Override
    public boolean shouldFilter() {
        return true;
    }

    //过滤器的具体逻辑根据业务自行编写。
    @Override
    public Object run() {
        RequestContext ctx = RequestContext.getCurrentContext();
        HttpServletRequest request = ctx.getRequest();
        String requestURI = request.getRequestURI();
        if (requestURI.equals("/user/login")) {
            return null;
        }
        String token = request.getHeader("token");
        if (StringUtils.isBlank(token) || !JwtKit.checkJWT(token)) {
            ctx.setSendZuulResponse(false);
            ctx.setResponseBody(JSON.toJSONString(Result.error(CodeMsg.ERROR_TOKEN)));
            ctx.setResponseStatusCode(200);
            //设置编码
            ctx.getResponse().setContentType("application/json;charset=UTF-8");
            return null;
        }
        String number = JwtKit.getValue(token);
        User user = userClient.getUserByNumber(number);
        if (null == user||user.getFlag()==1) {
            ctx.setSendZuulResponse(false);
            ctx.setResponseBody(JSON.toJSONString(Result.error(CodeMsg.FROZEN_USER)));
            ctx.setResponseStatusCode(200);
            //设置编码
            ctx.getResponse().setContentType("application/json;charset=UTF-8");
            return null;
        }
        return null;
    }
}